﻿using UnityEngine;

public class AStarGridMgr : BaseMono
{
	public static AStarGrid grid;

	//网格行列数
	public int Row = 4;
	public int Col = 4;

	/// <summary>
	/// 网格大小
	/// </summary>
	public float NodeSize = 1;

	/// <summary>
	/// 障碍物层
	/// </summary>
	public LayerMask WallLayer;

	//原点位置
	private float originX;
	private float originY;


//	public override void onAwake()
//	{
//		Init();
//	}

	public void Init(float size = 1)
	{
		NodeSize = size;

		originX = MyTrans.position.x;
		originY = MyTrans.position.y;
		WallLayer = 1 << LayerMask.NameToLayer("Wall");
		
		AStarRes.Init(Row, Col);
	}

	public void GenerateGrid(int row, int col)
	{
		Row = row;
		Col = col;
		grid = new AStarGrid(Row, Col, originX, originY, NodeSize, WallLayer);
		grid.OnDrawWall += AStarRes.DrawWall;
		grid.InitGrid();
	}

	public void Reset()
	{
		grid.OnDrawWall -= AStarRes.DrawWall;
	}

	public Vector3 ChooseSpawnPos() {
		int count = Row * Col;
		while (count > 0) {
			int x = Random.Range(0, Col);
			int y = Random.Range(0, Row);
			AStarNode node = grid.GetNode(x, y);
			if (node.CanMove)
			{
//				SetNodeCanMove(node.Position, false);
				return node.Position;
			}

			count--;
		}

		MyLog.LogError("Error :Can't Choose Spawn Positon!");
		return Vector3.zero;
	}

	public void SetNodeCanMove(Vector2 pos, bool canMove)
	{
		int x = (int) pos.x;
		int y = (int) pos.y;
		AStarNode node = grid.GetNode(x, y);
		if (node != null && node.CanMove != canMove)
		{
			node.CanMove = canMove;
			grid.SetDirty(node);
		}
	}

	private Vector3 from = new Vector3(0, 1, 0);
	private Vector3 to = new Vector3(0, 1, 0);
	void OnDrawGizmos() {
		from.y = to.y = 0;

		//Draw Columns
		from.y = originY;
		to.y = originY + Row * NodeSize;
		for (int i = 0; i <= Col; i++) {
			from.x = to.x = originX + i * NodeSize;
			Gizmos.DrawLine(from, to);
		}

		//Draw Rows
		from.x = originX;
		to.x = originX + Col * NodeSize;
		for (int i = 0; i <= Row; i++) {
			from.y = to.y = originY + i * NodeSize;
			Gizmos.DrawLine(from, to);
		}
	}
}
